/**
 * 
 */
package org.dragonfire.dasm.directives;

import java.util.ArrayList;

import org.dragonfire.dasm.Command;
import org.dragonfire.dasm.Listing;
import org.dragonfire.dasm.DirectiveManager.Directive;
import org.dragonfire.dasm.preprocessor.Preprocessor;

import com.stevesoft.pat.Regex;

/**
 * Includes another file into this file as assembler source<br />
 * <br />
 * Format:<br />
 * <code>#INCLUDE <i>&lt;file1&gt;</i>[,<i>&lt;file2&gt;</i>[,...]]</code><br />
 * <br />
 * Parameters:<br />
 * <table>
 * <tr>
 * <td><code>file1</code></td>
 * <td>(String) The name of the file to include</td>
 * </tr>
 * </table><br />
 * Errors:<br />
 * <table>
 * <tr>
 * <td><code>ERROR_STRING_REQUIRED</code></td>
 * <td>Thrown if <code>file1</code> is not a string</td>
 * </tr>
 * <tr>
 * <td><code>ERROR_FILE_OPERATION</code></td>
 * <td>Thrown if <code>file1</code> cannot be read</td>
 * </tr>
 * <tr>
 * <td><code>ERROR_FILE_NOT_FOUND</code></td>
 * <td>Thrown if <code>file1</code> does not exist in the filesystem</td>
 * </tr>
 * </table>
 * 
 * @see Preprocessor#preprocessFile(org.dragonfire.file.BufferedFile)
 * @see Includebin
 * @see Includesrc
 * @author Darth Android
 * @version 2.0
 */
public class Include extends Directive {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ArrayList<Listing> pass1(Command c) {
		// legacy mode only includes source files
		if (getCompiler().getBooleanParam("legacy-include"))
			return getDM().pass1(new Command("#includesrc", c.getParams()));
		ArrayList<Listing> list = new ArrayList<Listing>();
		for (int i = 0; i < c.getParams().length; i++) {
			String file = evalString(c.getParam(i));
			Regex extRegex = new Regex("\\<?.*\\.(.*)?\\>?");
			String ext = "";
			if (extRegex.search(file)) {
				ext = extRegex.stringMatched(1).toLowerCase();
			}
			if (ext.equals("bin"))
				list.addAll(getDM().pass1(new Command("#includebin", new String[] {
					c.getParam(i)
				})));
			else
				list.addAll(getDM().pass1(new Command("#includesrc", new String[] {
					c.getParam(i)
				})));
		}
		return list;
	}
}
